<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
	String port = request.getServerPort() == 80 ? "" : (":"+request.getServerPort());
	String path = request.getContextPath().replaceAll("/$","");
	String contextPath = request.getScheme()+"://"+request.getServerName()+port+path;
	pageContext.setAttribute("path_",path);
	pageContext.setAttribute("contextPath",contextPath);
	pageContext.setAttribute("resourceId", "0.0.2");
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <!--base-->
    <link rel="shortcut icon" href="${contextPath}/static/terminal/img/terminal.png" />
    <link rel="stylesheet" href='${contextPath}/static/terminal/css/sweetalert.css?resId=${resourceId}' >
    <script type="text/javascript" src="${contextPath}/static/terminal/js/sweetalert.min.js?resId=${resourceId}"></script>

    <script type="text/javascript" src="${contextPath}/static/terminal/js/jquery.min.js?resId=${resourceId}"></script> <!-- jQuery Library -->
    <script type="text/javascript" src="${contextPath}/static/terminal/js/jquery-ui.min.js?resId=${resourceId}"></script> <!-- jQuery Library -->
    <!-- Bootstrap -->
    <link rel="stylesheet" href="${contextPath}/static/terminal/css/bootstrap.min.css?resId=${resourceId}" >
    <link rel="stylesheet" href="${contextPath}/static/terminal/fonts/font-awesome-4.7.0/css/font-awesome.min.css?resId=${resourceId}" >
    <script type="text/javascript" src="${contextPath}/static/terminal/js/bootstrap.min.js?resId=${resourceId}"></script>

    <!--fileinput-->
    <link href="${contextPath}/static/terminal/js/fileinput/css/fileinput.min.css?resId=${resourceId}" media="all" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="${contextPath}/static/terminal/js/fileinput/js/fileinput.min.js?resId=${resourceId}" ></script>
    <script type="text/javascript" src="${contextPath}/static/terminal/js/fileinput/js/locales/zh.js?resId=${resourceId}"></script>
    <link rel="stylesheet" href="${contextPath}/static/terminal/css/webssh.term.css?resId=${resourceId}" >

    <!--term-->
    <link type="text/css" rel="stylesheet" href="${contextPath}/static/terminal/js/xterm/xterm.css?resId=${resourceId}">
    <script src="${contextPath}/static/terminal/js/xterm/xterm.js?resId=${resourceId}" type="text/javascript"></script>
    <script src="${contextPath}/static/terminal/js/xterm/addons/attach/attach.js?resId=${resourceId}" type="text/javascript"></script>
    <script src="${contextPath}/static/terminal/js/xterm/addons/fit/fit.js?resId=${resourceId}" type="text/javascript"></script>
    <script src="${contextPath}/static/terminal/js/xterm/addons/fullscreen/fullscreen.js?resId=${resourceId}" type="text/javascript"></script>
    <script type="text/javascript">
   		var path_ = "${path_}";
   		var contextPath = "${contextPath}";
   		var openNew = "${openNew}";
    </script>
    <script src="${contextPath}/static/terminal/js/webssh.term.js?resId=${resourceId}" type="text/javascript" ></script>

	<c:choose>
	    <c:when test="${!empty windowTitle}">
	        <title>${windowTitle}</title>
	    </c:when>
	    <c:otherwise>
	        <title>Terminal</title>
	    </c:otherwise>
	</c:choose>
    
    <style type="text/css">
        .error_msg {
            color: red;
            margin-top: 5px;
            font-size: 12px;
        }
    </style>
</head>

<body>

<div id="appbar" class="navbar navbar-default" role="navigation">
    <div class="container">
        <div>
            <ul class="nav navbar-nav">
                <li><a class="term-logo" href="${contextPath}" target="_blank" title="">Terminal</a></li>

				<li><a href="javascript:uploadModal()" title="上传文件" data-toggle="tooltip"><i aria-hidden="true" class="fa fa-upload"></i>&nbsp;上传文件</a></li>
				<li><a href="javascript:downloadModal()" title="下载文件" data-toggle="tooltip"><i aria-hidden="true" class="fa fa-download"></i>&nbsp;下载文件</a></li>
                <li><a href="javascript:window.open('${contextPath}/terminal/open.htm');" target="_blank" title="克隆会话"><i aria-hidden="true" class="fa fa-copy"></i>&nbsp;克隆会话</a></li>
                <li><a href="javascript:window.open('${contextPath}/terminal/openNew.htm');" target="_blank" title="其他终端"><i aria-hidden="true" class="fa fa-copy"></i>&nbsp;其他终端</a></li>
                <%-- <li class="dropdown">
                    <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" title="常用操作"><i aria-hidden="true" class="fa fa-server"></i>&nbsp;操作<b class="caret"></b></a>
                    <ul class="dropdown-menu" >
                        <li><a href="javascript:upload()" title="上传文件">&nbsp;上传文件</a></li>
                    </ul>
                </li>

                <li class="dropdown">
                    <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" title="打开终端"><i aria-hidden="true" class="fa fa-folder-open-o"></i>&nbsp;打开<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <c:forEach var="t" items="${terms}">
                            <li><a href="${contextPath}/terminal/ssh2.htm?id=${t.id}&csrf=${csrf}" target="_blank">${t.name}(${t.host})</a></li>
                        </c:forEach>
                    </ul>
                </li> 

                <li class="dropdown">
                    <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" title="主题"><i aria-hidden="true" class="fa fa-gear"></i>&nbsp;主题<b class="caret"></b></a>
                    <ul class="dropdown-menu theme" >
                        <li><a theme="default" href="javascript:void(0)"><span class="circle" style="background-color:#dddddd"></span>&nbsp;默认</a></li>
                        <li><a theme="gray" href="javascript:void(0)"><span class="circle" style="background-color:gray"></span>&nbsp;灰色</a></li>
                        <li><a theme="green" href="javascript:void(0)"><span class="circle" style="background-color:green"></span>&nbsp;绿色</a></li>
                        <li><a theme="black" href="javascript:void(0)"><span class="circle" style="background-color:black"></span>&nbsp;黑色</a></li>
                    </ul>
                </li>--%>

                <!-- <li><a href="javascript:closeTerminal();" title="退出终端" data-toggle="tooltip"><i aria-hidden="true" class="fa fa-power-off"></i>&nbsp;退出</a></li> -->

                <li id="sendNode" style="padding-top: 13px;margin-left: 15px;">
                    <label style="color:#777;font-weight: normal; "><i aria-hidden="true" class="fa fa-send"></i>&nbsp;<span id="sendLabel">命令</span></label>&nbsp;&nbsp;<input id="sendInput" class="send-input" size="30" placeholder="发送到所有终端会话请在这里输入" type="text">
                    &nbsp;<div class="btn btn-success btn-sm" id="sendBtn">&nbsp;&nbsp;发送&nbsp;&nbsp;</div>
                </li>
                <li style="padding-top: 13px;margin-left: 100px;"><div onclick="javascript:closeTerminal();" class="btn btn-success btn-sm" ><i aria-hidden="true" class="fa fa-power-off"></i>&nbsp;&nbsp;退出&nbsp;</div></li>
                <!-- <li style="float: right;margin-right: 15px;"><a href="" target="_blank"><i aria-hidden="true" class="fa fa-github" style="font-size:35px;position:absolute;top:8px"></i></a></li> -->
            </ul>
        </div>
    </div>
</div>
<!-- 修改密码弹窗 -->
<div class="modal fade" id="sshModal" data-backdrop="static" data-keyboard="false" 
	tabindex="-1" role="dialog" aria-hidden="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <!-- <button class="close btn-float" data-dismiss="modal" aria-hidden="true" onclick="closeWin();"><i class="md md-close"></i></button> -->
                <h4 id="sshTitle" style="color: red;font-size: 13px;">请输入当前用户密码或修改登陆信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form" id="sshform">
                    <div class="form-group" style="margin-bottom: 4px;">
                        <label for="sshname" class="col-md-3 control-label"><i class="glyphicon glyphicon-leaf"></i>&nbsp;&nbsp;名&nbsp;&nbsp;称&nbsp;&nbsp;：</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control " id="sshname" placeholder="请输入终端的实例名称"
                                   value="${terminal.name}">&nbsp;&nbsp;<label class="error_msg"
                                                                               id="sshname_lab"></label>
                        </div>
                    </div>

                    <div class="form-group" style="margin-bottom: 4px;">
                        <label for="sshhost" class="col-md-3 control-label"><i class="glyphicon glyphicon-tag"></i>&nbsp;&nbsp;地&nbsp;&nbsp;址&nbsp;&nbsp;：</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control " id="sshhost" placeholder="请输入主机地址(IP)"
                                   value="${terminal.host}">&nbsp;&nbsp;<label class="error_msg"
                                                                               id="sshhost_lab"></label>
                        </div>
                    </div>


                    <div class="form-group" style="margin-bottom: 4px;">
                        <label for="sshport" class="col-md-3 control-label"><i
                                class="glyphicon glyphicon-question-sign"></i>&nbsp;&nbsp;端&nbsp;&nbsp;口&nbsp;&nbsp;：</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control " id="sshport"
                                   placeholder="请输入端口" value="${terminal.port}">&nbsp;&nbsp;<label class="error_msg"
                                                                                                   id="sshport_lab"></label>
                        </div>
                    </div>

                    <div class="form-group" style="margin-bottom: 4px;">
                        <label for="sshuser" class="col-md-3 control-label"><i class="glyphicon glyphicon-user"></i>&nbsp;&nbsp;帐&nbsp;&nbsp;号&nbsp;&nbsp;：</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control " id="sshuser"
                                   placeholder="请输入账户" value="${terminal.userName}">&nbsp;&nbsp;<label class="error_msg" id="sshuser_lab"></label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="sshpwd" class="col-md-3 control-label"><i class="glyphicon glyphicon-lock"></i>&nbsp;&nbsp;密&nbsp;&nbsp;码&nbsp;&nbsp;：</label>
                        <div class="col-md-9">
                            <input type="password" class="form-control " id="sshpwd"
                                   placeholder="请输入密码"/>&nbsp;&nbsp;<label class="error_msg" id="sshpwd_lab"></label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer" style="text-align:center">
                    <button type="button" class="btn btn-sm" id="sshbtn" onclick="saveSsh()">登陆</button>
                    <!-- &nbsp;&nbsp;
                    <button type="button" class="btn btn-sm" onclick="resetForm()">重置</button> -->
            </div>
        </div>
    </div>
</div>
<div id="terminal-container"></div>

<div id="upload_push" class="modal fade" data-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">文件上传</h4>
            </div>
            <div class="modal-body">
                <form enctype="multipart/form-data">
                    <div class="input-group" style="padding-bottom:12px">
                        <span class="input-group-addon">上传路径</span>
                        <input type="text" id="fileinputPath" class="form-control col-lg-13" placeholder="请输入文件上传路径,默认在当前终端路径下">
                    </div>
                    <input id="file" name="file" type="file" multiple class="file-loading">
                    <div id="errorBlock" class="help-block"></div>
                </form>
            </div>
        </div>
    </div>
</div>
<div id="down_push" class="modal fade" data-backdrop="false" style="bottom: auto;left: auto;">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">文件下载</h4>
            </div>
            <div class="modal-body">
                  <div class="input-group" style="padding-bottom:12px">
                      <span class="input-group-addon">文件路径</span>
                      <input type="text" id="downloadFilePath" class="form-control col-lg-12" placeholder="请输入文件路径,默认当前终端路径下的文件" required="required">
                      <span class="input-group-btn">
						<button class="btn btn-primary" type="button" onclick="downloadFile()">下载 </button>	
					</span>
                </div>
				<div id="errorDownLoad" class="help-block" style="color:red;font-weight: bold;"></div>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript">
    var fileinputSSHId = guid();
    $(document).ready(function () {
        opencronTerm =  new OpencronTerm('${token}','${csrf}','${theme}');
        //去掉a点击时的虚线框
        $(".container").find("a").focus(function () {
            this.blur();
        })

        $(".theme").find("a").click(function () {
            opencronTerm.theme($(this).attr("theme"));
        });

        $("#terminal-container").css({
            "padding-top":$("#appbar").outerHeight()+5+"px"
        });

        $('#file').fileinput({
            language: 'zh',
            allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash'],
            previewFileType: 'any',
            showPreview : true,//开启预览，文件过大，可能会卡死浏览器
            browseOnZoneClick:false,
            uploadUrl : '${contextPath}/terminal/upload.do',
            removeLabel : "删除",
            showCaption: true, //是否显示标题,
            dropZoneEnabled:true,
            dropZoneTitle:"拖拽文件到这里来上传...",
            resizeImage: false,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            initialCaption: "请选择要上传的文件",
            maxFileSize:104857600,//文件最大100M
            allowedFileExtensions : null,
            elErrorContainer: '#errorBlock',
            uploadExtraData: function(){
            	return {
            		token : fileinputSSHId,
            		path : $("#fileinputPath").val()
            	}
            }
        }).on("fileuploaded", function(event, data) {
            if (!data.response) {
                alert('文件格式类型不正确');
            }else if (data.response.success == "false") {
               window.setTimeout(function () {
                   $("#upload_push").find(".progress-bar-success").addClass("progress-bar-danger").removeClass("progress-bar-success");
                   $(".file-actions").find(".glyphicon-ok-sign").addClass("text-danger glyphicon-remove-sign").removeClass("glyphicon-ok-sign text-success");
                   var error;
                   if(data.response.msg){
                	   error = '<li><b>1): </b>' + data.response.msg + '</li>';
                   }else{
                	   error = '<li><b>1): </b>文件大小太大,上传失败</li>' +
                       '<li><b>2): </b>上传路径是当前路径,且控制台正在实时输出日志(无法获取当前路径)</li>';
                   }
                   var uperrorhtml = '<span class="close kv-error-close" onclick="colseUpError()">×</span><ul><li><b>上传失败: (可能有以下原因)</b></li>' +
                       error + '</ul>';
                   $(".file-error-message").css({"margin":"8px 0px"});
                    $("#errorBlock").html(uperrorhtml).show();
               },300);
            }
        }).on("filepreupload", function(event, data){
        	opencronTerm.socket.send('action_uploadFile.do:' + fileinputSSHId);
        });
        
        $('#down_push').draggable({
			cursor: "move",
			handle: '.modal-header'
		});
    });
	
    function saveSsh() {
	    $(".error_msg").empty();
	
	    var user = $("#sshuser").val();
	    var name = $("#sshname").val();
	    var pwd = $("#sshpwd").val();
	    var port = $("#sshport").val();
	    var host = $("#sshhost").val();
	    var falg = true;
	
	    if (!name) {
	        $("#sshname_lab").text("终端实例名称不能为空");
	        falg = false;
	    } else {
	        if (name.length > 20) {
	            $("#sshname_lab").text("终端实例名称输入太长不合法");
	            falg = false;
	        }
	    }
	
	    if (!host) {
	        $("#sshhost_lab").text("机器地址不能为空");
	        falg = false;
	    } else {
	        var reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
	        //验证是否为网址
	        var objExp = new RegExp(reg);
	        if (!objExp.test(host)) {
	            //验证是否为IP
	            reg = /^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;
	            if (!reg.test(host)) {
	                $("#sshhost_lab").text("机器地址不合法,必须你网址或者IP");
	                falg = false;
	            }
	        }
	    }
	
	    if (!port) {
	        $("#sshport_lab").text("连接端口不能为空");
	        falg = false;
	    } else {
	        if (isNaN(port)) {
	            $("#sshport_lab").text("连接端口输入不合法,必须为数字");
	            falg = false;
	        } else {
	            port = parseInt(port);
	            if (port < 0) {
	                $("#sshport_lab").text("连接端口输入不合法,不能为负数");
	                falg = false;
	            } else if (port > 65535) {
	                $("#sshport_lab").text("连接端口输入不合法,不能超过65535");
	                falg = false;
	            }
	        }
	    }
	
	    if (!user) {
	        $("#sshuser_lab").text("登陆账号不能为空");
	        falg = false;
	    } else {
	        if (user.length > 255) {
	            $("#sshuser_lab").text("登陆账号太长,不合法");
	            falg = false;
	        }
	    }
	
	    if (!pwd) {
	        $("#sshpwd_lab").text("登陆密码不能为空");
	        falg = false;
	    }
	
	    if (!falg) return;
	
	    var host = $("#sshhost").val();
	
	    $.ajax({
	        type: "POST",
	        url: "${contextPath}/static/terminal/login.do",
	        data: {
	            "name": name,
	            "userName": user,
	            "password": pwd,
	            "port": port,
	            "host": host
	        },
	        dataType: "html",
	        success: function (data) {
	            $("#sshModal").modal("hide");
	            data = JSON.parse(data);
	            if (data.status == "success") {
	            	if(data.name) document.title = data.name;
	                if(opencronTerm) opencronTerm.focus();
	            } else {
	                window.setTimeout(function () {
	                    $("#sshModal").modal("show");
	                    $("#sshTitle").html(data.msg);
	                    $("#sshpwd").val('');
	                    $("#sshpwd")[0].focus();
	                },100);
	            }
	        }
	    });
	}
	
	$("#sshform").keyup(function(event){
		if(event.keyCode ==13){
			saveSsh();
		}
	});
	$("#downloadFilePath").keyup(function(event){
		if(event.keyCode ==13){
			downloadFile();
		}
	});
	
	function resetForm() {
	    $(".error_msg").empty();
	    $("#sshuser").val('');
	    $("#sshuser")[0].focus();
	    $("#sshpwd").val('');
	}
    function colseUpError() {
        $("#errorBlock").empty().hide();
    }

    function uploadModal() {
        $("#down_push").modal('hide');
        $("#upload_push").modal('show');
        $("#fileinputPath").val('');
        $('#file').click();
    }
    function downloadModal() {
    	var down_push = $("#down_push");
    	down_push.modal('show');
    	$("#downloadFilePath")[0].focus();
    }
    function downloadFile() {
    	var path = $("#downloadFilePath").val();
    	if(!path){
    		$("#errorDownLoad").html('文件路径必须输入').show();
    		return;
    	}
	    opencronTerm.socket.send('action_uploadFile.do:' + fileinputSSHId);
        var form = $("<form method='post' style='display:none' target='_blank'>");
	    form.attr("action",'${contextPath}/terminal/download.do');
	    form.append($('<input type="hidden" name="path" value="' + path + '">'));
	    form.append($('<input type="hidden" name="token" value="' + fileinputSSHId + '">'));
	    $('body').append(form);
	    form.submit();
	    form.remove();
        $("#down_push").modal('hide');
        $("#downloadFilePath").val('');
        $("#errorDownLoad").empty().hide();
    }

    function closeTerminal() {
        swal({
            title: "",
            text: "您确定要退出终端吗？",
            type: "warning",
            showCancelButton: true,
            closeOnConfirm: true,
            confirmButtonText: "退出"
        }, function() {
        	if(opencronTerm){
	            opencronTerm.close();
            }
            window.close();
        });
    }
    function escapeHtml(text) {
        if(text){
            return text.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;") ;
        }
    }

    function unEscapeHtml(text) {
        if(text){
            return text.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"").replace(/&quot;/g,"").replace(/&#39;/,"'");
        }
    }
    function guid() {
   	  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
   	    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
   	    return v.toString(16);
   	  });
   	}
</script>

</body>
</html>